<?php

namespace app\common\model;

use think\Model;

/*规格属性Model*/

class SpecValModel extends Model
{
    /**
     * 格式化获取规格列表
     * $spec_category_id 规格分类id
     */
    public function getSpecList($spec_category_id)
    {
        cache("spec_category_list_" . $spec_category_id, null);
        if (cache("?spec_category_list_" . $spec_category_id)) {
            return cache("spec_category_list_" . $spec_category_id);
        } else {
            $list = db("spec_val")->where('type_id', $spec_category_id)->select();

            $result = [];
            if ($list->isEmpty()) {
                //没有返回空
                $result = '';
                return $result;
            } else {
                foreach ($list as $key => $value) {
                    if (!isset($result[$value['attr_id']])) {
                        $result[$value['attr_id']]['attr_name'] = $value['attr_name'];
                    }
                    $result[$value['attr_id']]['list'][] = $value;
                }
            }
            cache("spec_category_list_" . $spec_category_id, array_values($result), 3600);


            return array_values($result);
        }
    }


    /**
     * 获取商品过规格表单
     * $spec_category_id 规格分类id
     * $goods_id 商品id
     */
    public function getSpecValueHtml($spec_category_id, $goods_id = 0)
    {
        // 获取规格列表
        $spec_tree = $this->getSpecList($spec_category_id);
        if (empty($spec_tree)) {
            if ($spec_category_id == 0) {
                $msg = '请选择商品类型';
            } else {
                $msg = '该类型为空，请选择其他商品类型或编辑商品规格。';
            }
            return $msg;
        }
        $table_header = '';
        $spec_arr = [];
        $i = 0;

        //相互组合
        foreach ($spec_tree as $spec_info) {
            // $table_header .= '<th>' . $spec_info['attr_name'] . '</th>';
            $temp = [];
            foreach ($spec_info['list'] as $key => $value) {
                $value['html'] = '<td>' . $value['attr_value'] . '</td>';
                if ($i > 0) {
                    $value['sublist'] = $spec_arr;
                }
                $temp[] = $value;
            }
            $spec_arr = $temp;
            $i++;
        }

        //获取table_header 组合
        $table_header = $this->getTableHeader($spec_arr);
        $goods_attr_value_arr = [];
        //查询商品的属性值
        if ($goods_id > 0) {
            $goods_attr_value_list = db("market_spec")->where("goods_id", $goods_id)->select();
            if (!empty($goods_attr_value_list)) {
                foreach ($goods_attr_value_list as $key => $value) {
                    $goods_attr_value_arr[$value['spec_str']] = [
                        'stock' => $value['stock'],
                        'price' => $value['price'],
                        'image' => $value['image']
                    ];
                }
            }
        }

        $spec_html = $this->getTableRows($spec_arr, $goods_attr_value_arr);
        $table_header .= '<th>库存</th><th>价格</th><th>图片</th>';
        $table = '<table class="table table-hover table-bordered"><tr>' . $table_header . '</tr>' . $spec_html . '</table>';
        return $table;
    }


    /**
     * 获取表格头组合
     */
    private function getTableHeader($spec_arr, &$header = '')
    {
        if (is_array($spec_arr)) {
            $currentArr = current($spec_arr);
            $header .= '<th>' . $currentArr['attr_name'] . '</th>';
            if (empty($currentArr['sublist'])) {
                return $header;
            } else {
                $this->getTableHeader($currentArr['sublist'], $header);
            }
        }
        return $header;
    }


    /**
     * 递归获取多规格组合表格
     */
    private function getTableRows($spec_arr, $goods_attr_value_arr = [], $spec_ids = [], $html = '')
    {
        if (is_array($spec_arr)) {
            $result = '';
            $last_spec_ids = $spec_ids;
            foreach ($spec_arr as $key => $value) {
                $spec_ids = $last_spec_ids;
                $spec_ids[] = $value['id'];
                if (isset($value['sublist'])) {
                    $result .= $this->getTableRows($value['sublist'], $goods_attr_value_arr, $spec_ids, $html . $value['html']);
                } else {
                    $result .= $this->getTableRows($value['html'], $goods_attr_value_arr, $spec_ids, $html);
                }
            }
            return $result;
        } else {
            $spec_ids_str = implode("_", $spec_ids) . "_";
            if (isset($goods_attr_value_arr[$spec_ids_str])) {
                $spec_stock = $goods_attr_value_arr[$spec_ids_str]['stock'];
                $spec_price = $goods_attr_value_arr[$spec_ids_str]['price'];
                if (empty($goods_attr_value_arr[$spec_ids_str]['image'])) {
                    $spec_image = '';
                    $spec_image_preview = '';
                } else {
                    $spec_image = $goods_attr_value_arr[$spec_ids_str]['image'];
                    $spec_image_preview = cmf_get_image_preview_url($spec_image);
                }
            } else {
                $spec_stock = 0;
                $spec_price = 0;
                $spec_image = '';
                $spec_image_preview = '';
            }
            $input_html = <<<TPL
                <td><input type="number" class="form-control spec_stock" name="spec_stock[$spec_ids_str]" value="{$spec_stock}"></td>
                <td><input type="number" class="form-control spec_price" name="spec_price[$spec_ids_str]" value="{$spec_price}"></td>
                <td>
                    <input id="photo-{$spec_ids_str}" type="hidden" name="image[$spec_ids_str]" value="{$spec_image}">
                    <img id="photo-{$spec_ids_str}-preview" style="width: 50px;" src="{$spec_image_preview}">
                    <br>
                    <a href="javascript:uploadOneImage('图片上传','#photo-{$spec_ids_str}');">上传</a>
                </td>
TPL;
            return '<tr>' . $html . $spec_arr . $input_html . '</tr>';
        }
    }

    /**
     * 根据规格id字符串  获取规格名字
     */
    public static function getSpecNameByIdStr($spec_str = '', $limit = '-')
    {
        if (empty($spec_str)) {
            return '';
        }
        if (cache('allSpecs')) {
            $allSpecs = cache('allSpecs');
        } else {
            $allSpecs = self::field('id,attr_value')->select();
            cache('allSpecs', $allSpecs);
        }
        //作缓存
        $result = [];
        foreach (explode('_', trim($spec_str, '_')) as $value) {
            foreach ($allSpecs as $allSpec) {
                if ($allSpec['id'] == $value) {
                    array_push($result, $allSpec['attr_value']);
                    break;
                }
            }
        }
        return implode($limit, $result);
    }

}
